<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>记账本</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    li {
      list-style: none;
    }

    h2 {
      text-align: center;
    }

    .container {
      width: 500px;
      margin: 50px auto;
    }

    .inc-exp-container {
      border: 1px solid #eee;
      box-shadow: 0px 1px 1px 0px rgb(174, 174, 174);
      display: flex;
      text-align: center;
      height: 120px;
      align-items: center;
      margin: 20px 0;
    }

    .inc-exp-container>div {
      flex: 1;
    }

    .inc-exp-container>div:first-child {
      border-right: 1px solid #eee;
    }

    .inc-exp-container h4 {
      font-size: 20px;
      margin-bottom: 5px;
    }

    .inc-exp-container p {
      font-size: 30px;
    }

    #money-plus {
      color: #0f0;
    }

    #money-minus {
      color: #f00;
    }

    #list li {
      height: 40px;
      line-height: 40px;
      display: flex;
      justify-content: space-between;
      border: 1px solid #eee;
      box-shadow: 0px 1px 0px 0px rgb(174, 174, 174);
      margin-bottom: 10px;
      padding-left: 10px;
      padding-right: 15px;
      position: relative;
    }

    #list li .delete {
      width: 25px;
      height: 25px;
      line-height: 25px;
      text-align: center;
      background: rgb(242, 66, 66);
      color: #fff;
      position: absolute;
      left: -26px;
      top: 8px;
      display: none;
    }

    #list li:hover .delete {
      display: block;
      cursor: pointer;
    }

    #list li::after {
      content: '';
      display: block;
      width: 5px;
      height: 41px;
      position: absolute;
      right: 0;
    }

    #list li.minus::after {
      background: #f00;

    }

    #list li.plus::after {
      background: #0f0;
    }

    h3 {
      border-bottom: 1px solid rgb(158, 158, 158);
      /* padding-bottom: 20px; */
      line-height: 50px;
      margin-bottom: 20px;
    }

    input {
      display: block;
      width: 100%;
      height: 40px;
      border: 1px solid #ccc;
      outline: none;
      text-indent: 10px;
      margin: 10px 0;
    }

    button {
      width: 100%;
      height: 50px;
      border: 1px solid #ccc;
      background: rgb(157, 134, 242);
      color: #fff;
      cursor: pointer;
    }
  </style>
</head>

<body>
  <h2>记账小簿</h2>

  <div class="container">
    <h4>你的资金平衡</h4>
    <h1 id="balance">$0.00</h1>

    <div class="inc-exp-container">
      <div>
        <h4>收入</h4>
        <p id="money-plus" class="money plus">+$0.00</p>
      </div>
      <div>
        <h4>支出</h4>
        <p id="money-minus" class="money minus">-$0.00</p>
      </div>
    </div>

    <h3>收入&支出记录</h3>
    <ul id="list" class="list">
      <!-- <li class="minus"><span class="delete">X</span><span>买电脑</span><span class="money ">-16900</span></li>
      <li class="plus"><span class="delete">X</span><span>卖手机</span><span class="money ">+19800</span></li> -->
    </ul>

    <h3>收支条目添加</h3>
    <div id="form">
      <div class="form-control">
        <label for="text">明细</label>
        <input type="text" id="text" placeholder="输入明细..." />
      </div>
      <div class="form-control">
        <label for="amount">金额
          <br />
          (负数 - 支出, 正数 - 收入)</label>
        <input type="number" id="amount" placeholder="输入金额..." />
      </div>
      <button class="addTransition">添加</button>
    </div>
  </div>
  <script>
    const addBtn = document.querySelector('.addTransition')
    const textInput = document.querySelector('#text')
    const amountInput = document.querySelector('#amount')
    const listDom = document.querySelector('#list')
    const balance = document.getElementById('balance')
    const moneyPlus = document.getElementById('money-plus')
    const moneyMinus = document.getElementById('money-minus')
    let transactions = []

    init()

    //--------------------------- DOM相关 -----------------------------
    // 添加
    addBtn.addEventListener('click', function (e) {
      const text = textInput.value
      const amount = amountInput.value

      // 数据的存储
      const transaction = {
        id: Date.now(),//得到当前时间的毫秒数（时间戳） 作为id标识每一条记录
        text,
        amount
      }
      // dom li的增加
      insertLi(transaction)

      // 更新本地存储
      updateRecord(transaction)
    })
    // 删除 【因为li有后生成的部分，所以要用事件委托的方式绑定】
    listDom.addEventListener('click', function (e) {
      const target = e.target
      if (target.className === 'delete') {
        // 删除li
        const li = target.parentNode
        li.remove()
        // 删除数据记录
        // function fn1(item) {
        //   return item.id == li.id
        // }
        // const fn2 = () => { return '111' }
        transactions.splice(transactions.findIndex(item => item.id == li.id), 1)
        updateRecord()
      }
    })

    /**
     * @description: 初始化数据
     */
    function init() {
      transactions = getRecords()
      transactions.forEach((transaction) => {
        // 生成li
        insertLi(transaction)
      })
      updateResult()
    }

    /**
     * @description: 插入li
     * @param {*} transaction li的数据
     */
    function insertLi(transaction) {
      const li = document.createElement('li')
      li.id = transaction.id
      if (transaction.amount > 0) {
        li.className = 'plus'
      } else {
        li.className = 'minus'
      }
      li.innerHTML = `
        <span class="delete">X</span>
        <span>${transaction.text}</span>
        <span class="money">${transaction.amount > 0 ? '+' + transaction.amount : transaction.amount}</span>
      `
      listDom.appendChild(li)

      textInput.value = ''
      amountInput.value = ''
    }

    function updateResult() {
      const result = {
        income: 0,
        expenditure: 0,
        balance: 0
      }
      transactions.forEach(item => {
        if (item.amount > 0) {
          result.income += item.amount * 1
        } else {
          result.expenditure += item.amount * 1
        }
      })
      result.balance = result.income + result.expenditure

      // 更新dom
      moneyPlus.innerHTML = '¥' + result.income
      moneyMinus.innerHTML = '¥' + (0 - result.expenditure) //变正数显示
      balance.innerHTML = '¥' + result.balance
    }

    // ----------------------- 和本地存储相关 -----------------------------------
    /**
     * @description: 获取本地记录
     * @return {*} js化后的本地记录
     */
    function getRecords() {
      return JSON.parse(localStorage.getItem('transactions')) || [] //当本地存储中没有存过transactions的时候为了避免拿到的是null导致程序崩溃，用空数组做初始化赋值
    }

    /**
     * @description: 更新本地存储
     * @param {*} transaction 要添加的新纪录
     */
    function updateRecord(transaction) {
      if (transaction) { transactions.push(transaction) }
      localStorage.setItem('transactions', JSON.stringify(transactions)) // [object object]

      updateResult()
    }

    // const arr = [1, 2, 3, 4, 5]
    // const i = arr.findIndex((item) => {
    //   return item == 5
    // })
    // console.log(i);

  </script>
</body>

</html>